package com.gcloud.mesh.monitor.cloud;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gcloud.mesh.asset.dao.CloudResourceConfigDao;
import com.gcloud.mesh.asset.entity.CloudResourceConfigEntity;
import com.gcloud.mesh.dcs.dao.AppInstanceDao;
import com.gcloud.mesh.dcs.entity.AppInstanceEntity;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.header.vo.dcs.CloudResourceMetricVO;
import com.gcloud.mesh.header.vo.dcs.DescribeMetricVO;
import com.gcloud.mesh.sdk.GceSDK;

import me.zhyd.oauth.log.Log;
@Service
public class K8sMonitor implements ICloudBaseMonitor{
    @Autowired
    private AppInstanceDao instanceDao;
    @Autowired
    private CloudResourceConfigDao configDao;
	

	@Override
	public List<DescribeMetricVO> queryDescribeMetricLastList(String cloudResourceId) {
		GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
		List<AppInstanceEntity> instances = instanceDao.findByCloudResourceId(cloudResourceId);
		List<DescribeMetricVO> vos = null;
		if(instances != null && !instances.isEmpty()) {
			vos = new ArrayList<>();
			for(AppInstanceEntity instance : instances) {
				DescribeMetricVO vo = new DescribeMetricVO();
				vo.setInstanceId(instance.getInstanceId());
				vo.setInstanceName(instance.getName());
				vo.setMemVal("0");
				vo.setCupVal("0");
				vos.add(vo);
				try {
					Map<String,Object> object = gceSDK.namespaceMonitormetrics(instance.getInstanceId());
					if(object.get("cpuVal") != null){
						vo.setCupVal(String.valueOf(object.get("cpuVal")));
					}
					if(object.get("memoryVal") != null) {
						vo.setMemVal(String.valueOf(object.get("memoryVal")));
					}
				} catch (Exception e) {
					Log.error("调用namesapce监控数据置零:"+e.getMessage());
				}
			}
		}
		return vos;
	}


	@Override
	public CloudResourceMetricVO queryCloudResourceMetric(String cloudResourceId) {
		//获取资源的配置信息
		CloudResourceConfigEntity entity = configDao.findOneByProperty("cloud_resource_id", cloudResourceId);
		GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
		Map<String,Object> object = gceSDK.clusterMonitormetrics(entity.getClusterId());
		CloudResourceMetricVO vo = new CloudResourceMetricVO();
		vo.setCloudResourceId(cloudResourceId);
		if(object.get("cpuVal") != null){
			vo.setCupVal(String.valueOf(object.get("cpuVal")));
		}
		if(object.get("memoryVal") != null) {
			vo.setMemVal(String.valueOf(object.get("memoryVal")));
		}
		return vo;
	}

}
